<template>
    <div class="invitation-code-page">
       <div>
           <el-form>
                <el-form-item label="任务开始时间 ：">
                <div class="block">
                  <el-date-picker size="small" v-model="searchTime" type="datetimerange" @change="changeTime" :default-time="['00:00:00', '23:59:59']" range-separator="至" start-placeholder="开始日期"
                   end-placeholder="结束日期"></el-date-picker>
                </div>
              </el-form-item>
               <el-form-item>
                   <el-button class="search-btn" @click="searchData()">查&nbsp;&nbsp;询</el-button>
               </el-form-item>

           </el-form>
       </div>
       <div>
           <el-table :data="tableData" border>
               <el-table-column prop="date_info" label="日期"></el-table-column>
               <el-table-column prop="date_commission" label="收益(按任务开始统计)"></el-table-column>
               <el-table-column prop="finsh_promoter_income" label="收益(按任务完成时间统计)"></el-table-column>
               <!--<el-table-column prop="difference" label="差值" :formatter="getDifference"></el-table-column>-->
           </el-table>
       </div>
    </div>

</template>
<script>
import {apiPromoterIncomeList} from '../../request/api'
    export default {
        data(){
            return {
                tableData:[],
                searchForm: {
                    token: window.sessionStorage.getItem("token"),
                    createTime: ''
                },

                searchTime: []
            }
        },
        created () {
          this.writeCurrentDate()
          this.getTableData()

        },
        methods:{
          // 差值
          // getDifference(row){
          //   return this.commaOperation(row.date_commission, row.finsh_promoter_income, "-")
          // },
          // 含逗号运算 a (+|-) b, 默认求和
          commaOperation(a, b, operator = "+") {
            if (operator == "+" || operator == "-") {
              a = typeof a == "string"? a : a.toString()
              b = typeof b == "string"? b : b.toString()
              // 获取计算结果
              let resultFloat = 0.00
              switch (operator) {
                case "+":
                  resultFloat = (parseFloat(a.split(",").join(""))
                    + parseFloat(b.split(",").join(""))).toFixed(2)
                  return
                case "-":
                  resultFloat = (parseFloat(a.split(",").join(""))
                    - parseFloat(b.split(",").join(""))).toFixed(2)
              }
              return this.formatMoney(resultFloat)
            } else {
              console.log("operator参数异常(+|-):请填写 + 或 - ")
            }
          },
          // 字符串格式化金钱
          formatMoney(price) {
            // 处理负数
            price = typeof price != "string" ? price : parseFloat(price).toFixed(2)
            let characterAbs = ""
            if (price < 0) {
              price = Math.abs(price).toFixed(2)
              characterAbs = "-"
            }
            // 处理负数 end

            // 转字符串处理
            if (typeof price != "string") price = price.toString()
            // 裁剪整数
            let numberStr = price.slice(0, price.length - 3)
            // 裁剪小数及点
            let minNumber = price.slice(price.length - 3)
            // 给整数加逗号
            if (numberStr.length > 3) {
              // 拼接总价格数据
              numberStr = numberStr.split("").reverse().reduce((prev, next, index) => {
                return ((index % 3) ? next : (next + ',')) + prev
              })
              price = numberStr + minNumber
            }
            return characterAbs + price
          },
          writeCurrentDate() {
            // var date = new Date()
            // date.setDate(1)
            // var month = parseInt(date.getMonth() + 1)
            // var day = date.getDate()
            // if (month < 10)  month = '0' + month
            // // if (day < 10)  day = '0' + day
            // var standardTime = date.getFullYear() + '-' + month + '-' + day + ' 00:00:00'
            var startTime = new Date(new Date().toLocaleDateString()).getTime() - 7 * 24 * 60 * 60 * 1000 * 1
            // var startTime = new Date(standardTime).getTime()
            var endTime = new Date(new Date().toLocaleDateString()).getTime() - 24 * 60 * 60 * 1000 * 1
            this.searchTime = [startTime,endTime]
            this.searchForm.createTime = this.changeTimestamp(startTime) + ' - ' +  this.changeTimestamp(endTime)
          },
            getTableData (){
              this.$showLoading()
                apiPromoterIncomeList(this.searchForm).then(res =>{
                  // 价格合计
                  let totalPrice = res.data.map(item => item.date_commission).reduce((pre, cur, index) => {
                    let price = parseFloat(pre.toString().split(",").join("")) + parseFloat(cur.split(",").join(""))
                    // 精度转换
                    return price.toFixed(2)
                  }, 0)
                  // 完成时间合计
                  let totalFinishPrice = res.data.map(item => item.finsh_promoter_income).reduce((pre, cur, index) => {
                    cur = typeof cur == "string" ? cur : cur.toString()
                    let price = parseFloat(pre.toString().split(",").join("")) + parseFloat(cur.split(",").join(""))
                    // 精度转换
                    return price.toFixed(2)
                  }, 0)
                  // 差值
                  // let differencePrice = this.commaOperation(totalPrice, totalFinishPrice, "-")
                  res.data.push({
                    date_commission: this.formatMoney(totalPrice),
                    finsh_promoter_income: this.formatMoney(totalFinishPrice),
                    // difference: differencePrice,
                    date_info: "合计"
                  })
                  // 价格合计end
                    this.tableData = res.data
                    this.$hideLoading()
                }).catch(res => {
                    this.$hideLoading()
                    this.$message.error('数据加载失败')
                })
            },
            searchData(){
                if(!this.searchForm.createTime){
                  this.$message.error('时间不能为空')
                  return
                }
                this.getTableData()
            },
            changeTime(val){
                 if (this.searchTime == null) {
                     this.searchForm.createTime = ''
                } else{
                  // const startTimestamp = new Date(val[0]).getTime();
                  // const endTimestamp = new Date(val[1]).getTime();
                  // if ((endTimestamp - startTimestamp) >  24 * 60 * 60 * 1000) {
                  //    this.$message.error('查询范围不能超过一天');
                  //    this.writeCurrentDate()
                  //    return;
                  // }
                  this.searchForm.createTime =  this.changeTimestamp(val[0]) + ' - ' +  this.changeTimestamp(val[1])

                }
            },
            changeTimestamp(time){
                var d = new Date(time);
                var s = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
                return s
            },
        }
    }
</script>
<style lang="less" scoped>
@import '../../assets/css/common.css';
</style>
